import urllib.request as ur
import urllib.parse as up
import json



# 在使用百度实时翻译接口sug的时候出现了一个问题，对于用户输入复杂的语句，返回的data结果可能有异，可以加入try except关键字，即提升代码本身的健硕性

# 输入要翻译的内容word
def translate_input():
    word = input("请输入要翻译的内容（非中文翻译成中文，中文翻译成英文）：")
    data = {
        'query': word
    }
    return data,word

# 通过输入的内容判断，内容所属语言
def language_detect(data):
    data_url = up.urlencode(data)
    request = ur.Request(
        url='https://fanyi.baidu.com/langdetect',
        data=data_url.encode('utf-8'),
    )

    response = ur.urlopen(request).read()
    # print(response)
    ret = json.loads(response)
    # print(ret)
    translate = ret['lan']
    # print(translate)
    return translate

# 得到要翻译的内容和所属语言，进行翻译，默认翻译方式：非中文翻译成中文，中文翻译成英文
def translate(language,data,word):
    # 'transtype': 'translang',
    # 'transtype': 'realtime',
    # 'simple_means_flag': '3',
    # 'sign': '477811.239938',
    # 'token': '364644cb52d71a13c96acbe7818896d1',
    # 'domain': 'common',
    data = {
        'from': language,
        'to': 'zh',
        'query':word,
        'sign': '477811.239938',
        'token': '364644cb52d71a13c96acbe7818896d1',
    }
    data_url=up.urlencode(data)
    # ur.Request()中的url原本想着是下面的这个，但实际总是返回'errno': 997, 'error': 997。所以修改成http://fanyi.baidu.com/transapi
    # url='https://fanyi.baidu.com/v2transapi?from='+language+'&to=zh',
    # url='http://fanyi.baidu.com/transapi',
    # url='http://fanyi.baidu.com/basetrans',
    request=ur.Request(
        url='https://fanyi.baidu.com/v2transapi?from='+language+'&to=zh',
        headers={
            'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36',
            'Cookie':'BIDUPSID=B6349526E839181D05D388E6CC9DEEE1; PSTM=1577353092; BAIDUID=B6349526E839181D01E0B26715E40AAA:FG=1; MCITY=-%3A; BDUSS=BYYzZaamN-RENnR1A5cDVtSXhRRENJaktYOXpBeFFneDViWFRLMDdtLTdTY1plRVFBQUFBJCQAAAAAAAAAAAEAAACV7C4EZGttYWhhbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALu8nl67vJ5eUF; REALTIME_TRANS_SWITCH=1; FANYI_WORD_SWITCH=1; SOUND_SPD_SWITCH=1; HISTORY_SWITCH=1; SOUND_PREFER_SWITCH=1; BDRCVFR[Az4XYP37mB6]=mk3SLVN4HKm; H_PS_PSSID=; delPer=0; PSINO=2; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; Hm_lvt_64ecd82404c51e03dc91cb9e8c025574=1589784190,1589784196,1589784458,1589785030; Hm_lpvt_64ecd82404c51e03dc91cb9e8c025574=1589791060; yjs_js_security_passport=0107ce90bcc855fe6e2af2fd8077f66f9d607868_1589791061_js',
        },
        data=data_url.encode('utf-8'),
    )
    response=ur.urlopen(request).read()
    ret=json.loads(response)
    print(ret)

if __name__ == '__main__':
    data,word=translate_input()
    language_from=language_detect(data)
    translate(language_from,data,word)

